//
//  YYAlbumTableViewController.swift
//  CodeLibrary_Swift
//
//  Created by 陆文宇 on 2017/2/8.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit
import Photos

class YYAlbumTableViewController: UITableViewController {
    
    lazy var dataSource: Array<Dictionary<String, Any>> = []
    
    var assetCollectionTypes: YYPhotoHandler.AssetCollectionType
    var defaultType: YYPhotoHandler.AssetCollectionType
    var defaultTitle: String?
    
    init(assetCollectionTypes: YYPhotoHandler.AssetCollectionType, defaultType: YYPhotoHandler.AssetCollectionType, defaultTitle: String?) {
        self.assetCollectionTypes = assetCollectionTypes
        self.defaultType = defaultType
        self.defaultTitle = defaultTitle
        super.init(nibName: nil, bundle: nil)
        
        YYPhotoHandler.available(authorized: { 
            DispatchQueue.global().async {
                let albums: Dictionary<String, Any> = YYPhotoHandler.albums(with: self.assetCollectionTypes, defaultType: self.defaultType, defaultTitle: self.defaultTitle)
                self.dataSource.append(contentsOf: albums["albums"] as! Array<Dictionary<String, Any>>)
                
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    
                    if let _ = albums["defaultAlbumName"] {
                        self.pushPhotoCollectionViewController(with: albums["defaultAlbumIndex"] as! Int, animated: false)
                    }
                }
            }
        }) { 
            let label = UILabel(frame: CGRect(x: 10, y: 0, width: UIScreen.main.bounds.width - 20, height: 100))
            label.text = "此应用没有权限访问您的照片或视频。\n您可以在“隐私设置”中启用访问。"
            label.numberOfLines = 0
            label.textAlignment = .center
            self.tableView.addSubview(label)
            
            self.tableView.separatorStyle = .none
            self.tableView.isScrollEnabled = false
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        let cancelItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(cancel))
        navigationItem.rightBarButtonItem = cancelItem
        title = "照片"
        
        tableView.rowHeight = 60
        tableView.register(UINib(nibName: "YYAlbumTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
    }
    
    @objc func cancel() -> Void {
        dismiss(animated: true, completion: nil)
    }
    
    func pushPhotoCollectionViewController(with albumIndex: Int, animated: Bool) -> Void {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 4
        layout.minimumInteritemSpacing = 4
        layout.itemSize = CGSize(width: (UIScreen.main.bounds.size.width - 20) / 4, height: (UIScreen.main.bounds.size.width - 20) / 4)
        layout.sectionInset = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
        let photoCVC: YYPhotoCollectionViewController = YYPhotoCollectionViewController(collectionViewLayout: layout, assetCollection: dataSource[albumIndex]["album"] as! PHAssetCollection)
        photoCVC.title = dataSource[albumIndex]["title"] as? String
        navigationController?.pushViewController(photoCVC, animated: animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dataSource.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: YYAlbumTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YYAlbumTableViewCell

        // Configure the cell...
        let album: Dictionary<String, Any> = dataSource[indexPath.row]
        let image: UIImage? = album["image"] as? UIImage
        cell.albumImageView.image = image
        cell.albumNameLabel.text = "\(album["title"]!) (\(album["number"]!))"
        cell.accessoryType = .disclosureIndicator

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        pushPhotoCollectionViewController(with: indexPath.row, animated: true)
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
